const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
	throwOnNotFound: true
})
const _ = db.command;
const $ = db.command.aggregate
const globalConfig = require('../../config/index')

module.exports = async (event, context, root) => {
  const {
    OPENID
  } = cloud.getWXContext();
  // 验证该接口是否需要验证注册
  let parame = event.data;
//   try {
    let where = {
      openId: OPENID
    }

    // 当天的
    if (parame.isToday) {
		const today = new Date() // 获取当前日期  
      // 注意：JavaScript Date对象月份是从0开始的，所以月份要+1  
      const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime()
      // 计算当天的结束时间（注意：日期对象的最后一天是23:59:59，但时间戳是毫秒，所以+86399999毫秒）  
      const endDate = startDate + 86399999;
      where = {
        openId: OPENID,
        day: _.gte(startDate).and(_.lt(endDate)),
      }
    }

	var result = await db.collection('caipiao_log').where(where)
  .orderBy('day', 'desc') // 根据day字段进行倒序排序  
  .get();
	
	let list = result.data
	// for(let i=0;i<list.length;i++){
	// 	if( list[i].winning_numbers ){
	// 		let winning_numbers = list[i].winning_numbers.split(",").map(item=>{ return Number(item)<10&&item.length==1?'0'+item:''+item }).join(',')
	// 		await db.collection('caipiao_log').where({
	// 			_id: list[i]._id,
	// 		}).update({
	// 			data:{
	// 				is_winnings_updata:0,
	// 				winning_numbers:winning_numbers
	// 			}
	// 		})
	// 	}
	// }

    var res = {
      errcode: 200,
	  msg: '操作成功！',
	  list:list,
      result: {
        list: result.data
	  },
	  where:where,
      success: true,
      timestamp: new Date().getTime()
    }
//   } catch (error) {
//     var error_type = globalConfig.common.error_type(error.errCode);
//     var res = {
//       errcode: 404,
//       error: error,
//       msg: error_type.type,
//       result: error,
//       success: false,
//       timestamp: new Date().getTime()
//     }
//   }
  return res;
}
